﻿#_*_ coding: UTF-8 _*_

from core import uicomponents, db
from PyQt4 import QtGui, QtCore
from servers.root.definitions import *
import servers.quran.definitions

def addRoot():

	rootNameList = QtCore.QStringList()
	rootList = qRoot.giveAllRoots()
	for root in rootList:
		rootNameList.append(QtCore.QString.fromUtf8(root.word))
	
	root = QtGui.QInputDialog.getItem(None, u'انتخاب ريشه', u'ريشه', rootNameList, 0, False)
	if not root[1]:
		return

	for aroot in rootList:
		if aroot.word == root[0]:
			for r in uicomponents.SharedUi.selectionStartWord.roots:
				if r.root.id == aroot.id:
					break
			else:	
				uicomponents.SharedUi.selectionStartWord.roots.append(qWordRoot())
				uicomponents.SharedUi.selectionStartWord.roots[-1].root = aroot
	
	db.session.flush()


def showRoot():
	s = "<font face='B Davat' size=16>"
	for r in uicomponents.SharedUi.selectionStartWord.roots:
		s = s+ r.root.word 
		s = s + "<br>"
	if len(uicomponents.SharedUi.selectionStartWord.roots)==0:
		s = s + "ريشه ندارد"
	s = s + "</font>"	
	uicomponents.SharedUi.textDialog.showMe(u'ريشه ها',QtCore.QString.fromUtf8(s))

rootMenu = QtGui.QMenu(u'ريشه')

setWordRoot = QtGui.QAction(u'تعيين ريشه', None)
QtCore.QObject.connect(setWordRoot, QtCore.SIGNAL('triggered()'), addRoot)
rootMenu.addAction(setWordRoot)

showWordRoot = QtGui.QAction(u'نمايش ريشه', None)
QtCore.QObject.connect(showWordRoot, QtCore.SIGNAL('triggered()'), showRoot)
rootMenu.addAction(showWordRoot)


uicomponents.SharedUi.wordPopupMenu.addMenu(rootMenu)
uicomponents.SharedUi.modulesListMenu.addMenu(rootMenu)


def commentWord(word,w):
	s = ""
	for root in word.roots:
		s += root.root.word + ", "
	return w+"{%s}" % s

servers.quran.definitions.quranWordCommenters['ريشه']=commentWord


def changeAdvanceSearchQueryRoot(text):
	query = unicode(servers.quran.definitions.advSearchQuery['widget'].text())
	tindex = query.find("root{")
	if tindex>-1:
		if len(unicode(text).strip())==0:
			query = query[:tindex]+query[tindex+query[tindex:].find("}")+1:]
		else:	
			query = query[:tindex] + "root{" + text + "}" + query[tindex+query[tindex:].find("}")+1:]
	else:
		query += " root{" + text + "} "
	servers.quran.definitions.advSearchQuery['widget'].setText(query)

servers.quran.definitions.advSearchPlugins['root'] = {}
servers.quran.definitions.advSearchPlugins['root']['layout'] = QtGui.QVBoxLayout()
servers.quran.definitions.advSearchPlugins['root']['layout'].addWidget(QtGui.QLabel(u'شامل ريشه'))
rootAdvancedSearchQuery = QtGui.QLineEdit()
servers.quran.definitions.advSearchPlugins['root']['layout'].addWidget(rootAdvancedSearchQuery)
QtCore.QObject.connect(rootAdvancedSearchQuery,QtCore.SIGNAL("textChanged(QString)"),changeAdvanceSearchQueryRoot)

print "root module Added!"
